<template>
    <div>
        <Search v-model="queryModel.query" 
        :loading="queryLoaing"
        @search="queryModel.pagenum=1;
        getUserList()"
           @click="model={};$refs.d.show()"
        >
            添加用户
        </Search>
        <!-- 搜索框 -->
        <!-- <div class="deng">
            <el-input placeholder="请输入内容" 
            v-model="queryModel.query">
                 <el-button 
                 :loading="queryLoaing"
                 @click="getUserList"
                 slot="append" 
                 icon="el-icon-search"></el-button>
            </el-input>
            <el-button type="primary"
             @click="model={};$refs.d.show()"
             
            >添加用户</el-button>
        </div> -->
       <!-- 表格 -->
       <MyTable
       :loading="tableLoading"
       :data="list"
       :cols="cols"
       :total="total"
       v-model="queryModel"
       @change="getUserList"
       >
           <template v-slot:state="{row}">
                    <el-switch 
                    @change="switchState(row)"
                    v-model="row.mg_state">
                        
                    </el-switch>
                </template>
                  <template v-slot:action="{row}">
                       <el-button type="primary" size="mini"
                        @click="model={...row};$refs.d.show()">
                        编辑</el-button>
                        <el-button type="danger" size="mini"
                        @click="deleteUser(row)"
                        >删除</el-button>
                   <el-button type="warning" size="mini"
                   @click="model={...row};
                   getRoleList()
                   "
                   >分配角色</el-button>
                </template>
       </MyTable>
        <!-- <el-table v-model="queryModel" v-loading="tableLoading" row-key="id" :data="list" border>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="姓名" prop="username"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="电话" prop="mobile"></el-table-column>
            <el-table-column label="角色" prop="role_name"></el-table-column>
            <el-table-column label="状态" >
                <template v-slot="{row}">
                    <el-switch 
                    @change="switchState(row)"
                    v-model="row.mg_state">
                        
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="270px" align="center">
                <template v-slot="{row}">
                       <el-button type="primary" size="mini"
                        @click="model={...row};$refs.d.show()">
                        编辑</el-button>
                        <el-button type="danger" size="mini"
                        @click="deleteUser(row)"
                        >删除</el-button>
                   <el-button type="warning" size="mini"
                   @click="model={...row};
                   getRoleList()
                   "
                   >分配角色</el-button>
                </template>
                   
                 
            </el-table-column>
        </el-table>
        <el-Pagination
        row-key='1'
            @size-change="
            (v)=>{
              queryModel.pagesize=v;
              getUserList()
            }"
           @current-change="
           (v)=>{
            queryModel.pagenum=v;
            getUserList()
           }"
            :current-page="queryModel.pagenum"
            :page-sizes="[10, 20, 30, 40,50,]"
            :page-size="queryModel.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        >
        </el-Pagination> -->
        <!-- 添加修改 -->
        <MyDialog  :title="title+'用户'" ref="d" @confirm="confirm">
                <el-form ref="form" label-width="70px" :model="model" :rules="rules">
                 <el-form-item label="用户名" prop="username">
                    <el-input  :disabled="!!model.id" v-model="model.username"></el-input>
                 </el-form-item>
                 <el-form-item v-if="!model.id" label="密码" prop="password">
                    <el-input :maxlength="15" type="password" v-model="model.password"></el-input>
                 </el-form-item>
                 <el-form-item label="邮箱" prop="email">
                    <el-input  v-model="model.email"></el-input>
                 </el-form-item>
                 <el-form-item label="手机" prop="mobile">
                    <el-input  v-model="model.mobile"></el-input>
                 </el-form-item>
              
             </el-form>
        </MyDialog>
        <!-- <el-dialog 
        :close-on-click-model="false"
        :title="title+'用户'" :visible.sync="visible">
             <el-form ref="form" label-width="70px" :model="model" :rules="rules">
                 <el-form-item label="用户名" prop="username">
                    <el-input  :disabled="!!model.id" v-model="model.username"></el-input>
                 </el-form-item>
                 <el-form-item v-if="!model.id" label="密码" prop="password">
                    <el-input :maxlength="15" type="password" v-model="model.password"></el-input>
                 </el-form-item>
                 <el-form-item label="邮箱" prop="email">
                    <el-input  v-model="model.email"></el-input>
                 </el-form-item>
                 <el-form-item label="手机" prop="mobile">
                    <el-input  v-model="model.mobile"></el-input>
                 </el-form-item>
              
             </el-form>
             <div slot="footer">
                <el-button>取消</el-button>
                <el-button type="primary" :loading="confirmLoading" @click="confirm">确定</el-button>
             </div>
        </el-dialog> -->
        <!-- 分配角色 -->
        <MyDialog title="分配角色" ref="ad"   @confirm="changeRole">
                 <p>当前的用户：{{model.username}}</p>
        <p>当前的角色：{{model.role_name}}</p>
        <p>分配新角色:
            <el-select v-model="model.rid" >
                <el-option v-for="item in roles"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
                >
                </el-option>
            </el-select>
        </p> 
        </MyDialog>
              <!-- <el-dialog 
        :close-on-click-model="false"
        title="分配角色" :visible.sync="assignVisible">
        this.$refs.dialog.stop()
        <p>当前的用户：{{model.username}}</p>
        <p>当前的角色：{{model.role_name}}</p>
        <p>分配新角色:
            <el-select v-model="model.rid" >
                <el-option v-for="item in roles"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
                >
                </el-option>
            </el-select>
        </p> 
             <div slot="footer">
                <el-button @click="assignVisible=false">取消</el-button>
                <el-button type="primary" 
                :loading="confirmLoading" 
                @click="changeRole"
                >确定</el-button>
             </div>
        </el-dialog> -->
        <!-- <el-form :model="model">
            <el-form-item :rules="item.rules"
            :prop="key"
             :label="item.title" v-for="(item,key) in opts" :key="key">
                <el-input 
                v-model="model[key]"
                :type="item.type"
                :maxlength="item.max"
                :disabled="item.dis"
                :placeholder="item.ph"
                 v-if="item.tag==='input'"></el-input>
            </el-form-item>
        </el-form> -->
        {{model}}
        <MyForm v-model="model" :opts="opts"></MyForm>
    </div>
</template>

<script>
import {getUsers,changeState,addUser,updataUser, delUser} from'../api/user'
import {getRoles, updateRole} from "api/rights";
import { pageMixins } from "@/mixins/baseMixins";

const opts={
    username:{
        title:'用户名',
        required:true,
      
        max:10,
        ph:'请输入用户名',
        rules:[
        {max:10}]
    },
    password:{
        title:'密码',
        required:true,
      
        type:"password",
        max:15,
        ph:'请输入密码',
    }
};

    export default {
        mixins:[pageMixins],
        name:'users',
        data() {
            return {
                opts,
                // /**
                //  * 数据列表
                //  */
                // list:[],
                
                //添加修改模型
                model:{},
                //规则
                rules:{
                   username:[
                    {required:true,message:'用户名不能为空',},
                   {min:3,max:10,message:'用户名长度为3-10位'}
                   ],
                   password:[
                    {required:true,message:'密码不能为空',},
                   {min:6,max:15,message:'密码长度为6-15位'}
                   ],
                   email:[
                    {required:true,message:'用户名不能为空'},
                    {type:'email',message:'邮箱格式不正确'}
                   ],
                   mobile:[
                     {required:true,message:'手机不能为空'},
                     {pattern:/^1[3-9]\d{9}$/,message:"手机格式不正确"}
                   ]
                },
                // /**
                //  * 查询loading
                //  */
                // queryLoaing:false,
            
                // /**
                //  * 总条数
                //  */
                // total:0,
                // /**
                //  * 查询模型
                //  */
                // queryModel:{
                //    query:'',
                //    pagenum:1,
                //    pagesize:20,
                // },

                /**
                 * 角色列表
                 */
                roles:[],
           
                /**
                 * 表格loading
                 */
                tableLoading:false,
                /**
                 * 列
                 */
                cols:[
                    {
                     title:"#",
                     type:"index",
                    },
                    {
                     title:"姓名",
                     name:"username",
                    },
                    {
                     title:"邮箱",
                     name:"email",
                    },
                    {
                     title:"电话",
                     name:"mobile",
                    },
                    {
                     title:"角色",
                     name:"role_name",
                    },
                    {
                     title:"状态",
                     slot:"state",
                    },
                    {
                     title:"操作",
                     slot:"action",
                     align:"center",
                     width:270
                    },
                ]
                  
                
            }
        },
        created (){
             this.getUserList()//添加用户
             
        },
        computed:{
           title(){
            return this.model.id?'修改':'添加';
           }
        },
      methods:{
        /**
         * 修改角色
         */
        async changeRole(){
            const ad=this.$refs.ad
           try {
             this.$refs.ad.start()
            // this.confirmLoading=true
              await updateRole(this.model.id,this.model.rid)
              this.$m.success('角色修改成功')
              ad.hide()
            //   this.$refs.ad.show();
        
              this.getUserList()
           } catch (error) {}
            //  this.confirmLoading=false
            ad.stop();
          
        },
        /**[p]
         * 获取角色列表
         */
        async getRoleList(){
            try {
                this.tableLoading=true
                this.roles=await getRoles()
              const rid=this.roles.find
              (c=>c.roleName===this.model.role_name)?.id??
              this.roles[0].id;
              this.$set(this.model,"rid",rid)
              this.$refs.ad.show();
              this.$refs.ad.start();
                this.assignVisible=true
            } catch (error) {
                console.log(error)
            }
            this.tableLoading=false
        },
        /**
         * 删除用户
         */
        async deleteUser({id,username}){
            let res;
            try {
                res=await this.$myConfirm(`你确定要删除吗【${username}】吗？`);
                
                await delUser(id)
                this.$m.success('删除成功');
                this.getUserList()
            } catch (error) {
                
            }
            res&&res()
        },
        /**
         * 提交添加修改
         */
        async confirm(){
            const d=this.$refs.d
           try {
             await this.$refs.form.validate();
             d.start();
            //  this.confirmLoading=true
            //  await (this.model.id ? updataUser : addUser)(this.model);
              await (this.model.id ? updataUser : addUser)(this.model);
              d.hide()
             this.$m.success(this.title+'成功')
             this.getUserList()
               this.visible=false
           } catch (error) {
               console.log(error);
           }
           d.stop()
        },
           async switchState({id,mg_state}){
                try {
                   await changeState(id,mg_state);
                   this.$m.success('状态变更成功')
                   this.getUserList()
                } catch (error) {
                
                }
           },
         /**
          * 获取用户列表
          */
         async getUserList(){
            try {
                this.queryLoaing=true
                const {total,users}=await getUsers(this.queryModel)
                this.total=total;
                this.list=users;
            } catch (error) {}
                 this.queryLoaing=false

         }
      }
    }
</script>

<style scoped lang="scss">
.deng{
    display: flex;
    width: 500px;
}
table{
    width: 100%;
    height: 30px;
    line-height: 30px;
    border: 1px solid #ebeef5;
    margin-top: 15px;
    box-sizing: border-box;
    color: #606266;
    margin-bottom: 10px;
}
.zwshuj{
    text-align: center;
}

</style>